using MyTimer;
using Services;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DialogUI_TextBox : MonoBehaviour
{
    private TextBox textBox;
    private Text speakerName;
    private Image nameBackground;
    private DialogSystem dialogSystem;
    private GlobalGameCycle gameCycle;
    private TypeWriterExtend extend;

    private void Awake()
    {
        gameCycle = ServiceLocator.Get<GlobalGameCycle>();
        EventSystem eventSystem = ServiceLocator.Get<EventSystem>();
        textBox = GetComponentInChildren<TextBox>();
        speakerName = GetComponentInChildren<Text>();
        dialogSystem = GetComponentInParent<DialogSystem>();
        nameBackground = GetComponentsInChildren<Image>()[1];
        eventSystem.AddListener<EGameState, EGameState>(EEvent.GameStateChange, OnGameStateChange);
    }

    private void Start()
    {
        extend = new TypeWriterExtend();
        extend.Initialize(textBox.TypeWriter);
        dialogSystem.ShowSingleDialog += ShowText;
        dialogSystem.ShowSelection += OnShowSelection;
        dialogSystem.EndSelection += OnEndSelection;
    }

    private void ShowText(SingleDialog dialog)
    {
        speakerName.text = dialog.speaker;
        if (dialog.speaker != "")
            nameBackground.color = Color.white;
        else
            nameBackground.color = Color.clear;
        textBox.ShowText(dialog.content);
    }

    private void CheckMouseClick()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (textBox.TypeWriter.Completed)
                dialogSystem.MoveNext();
            else
                textBox.TypeWriter.ForceComplete();
        }
    }

    private void OnShowSelection(List<string> list, DialogNode[] nodes)
    {
        gameCycle.RemoveFromGameCycle(EInvokeMode.Update, CheckMouseClick);
    }

    private void OnEndSelection()
    {
        gameCycle.AttachToGameCycle(EInvokeMode.Update, CheckMouseClick);
    }

    private void OnGameStateChange(EGameState from, EGameState to)
    {
        switch (from)
        {
            case EGameState.Dialog:
            case EGameState.DialogInPerformance:
                gameCycle.RemoveFromGameCycle(EInvokeMode.Update, CheckMouseClick);
                break;
        }
        switch (to)
        {
            case EGameState.Dialog:
            case EGameState.DialogInPerformance:
                MyReset();
                gameCycle.AttachToGameCycle(EInvokeMode.Update, CheckMouseClick);
                break;
        }
    }

    private void MyReset()
    {
        speakerName.text = "";
        nameBackground.color = Color.clear;
    }
}
